package com.itheima.server;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

// 消息模型类
public class Message {
    private String content;
    private String timestamp;

    public Message(String content, Date timestamp) {
        this.content = content;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        this.timestamp = sdf.format(timestamp);
    }

    // 从JSON字符串解析消息
    public static Message fromJson(String json) {
        // 简单解析，实际应用中建议使用Jackson或Gson
        try {
            // 提取content字段
            String content = json.substring(json.indexOf("\"content\":\"") + 11);
            content = content.substring(0, content.indexOf("\""));
            return new Message(content, new Date());
        } catch (Exception e) {
            throw new RuntimeException("解析消息失败", e);
        }
    }

    // 转换为JSON字符串
    public String toJson() {
        return String.format("{\"content\":\"%s\",\"timestamp\":\"%s\"}",
                escapeJson(content), timestamp);
    }

    // 转义JSON特殊字符
    private String escapeJson(String text) {
        if (text == null) return "";
        return text.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    public String getContent() {
        return content;
    }

    public String getTimestamp() {
        return timestamp;
    }
}

